package actor

import (
	"fmt"
	"time"

	"github.com/AsynkronIT/protoactor-go/actor"
	alog "github.com/AsynkronIT/protoactor-go/log"
	"github.com/AsynkronIT/protoactor-go/mailbox"
	"github.com/AsynkronIT/protoactor-go/remote"

	ndebug "nggs/debug"
	nlog "nggs/log"
	nrpc "nggs/rpc"
)

var RootContext = actor.EmptyRootContext

func DefaultDecider(reason interface{}) actor.Directive {
	gLogger.Error("crashed, reason: %#v, stack: %s", reason, ndebug.Stack())
	return actor.StopDirective
}

func Init(logLevel alog.Level, logger nlog.ILogger) {
	actor.SetLogLevel(logLevel)
	remote.SetLogLevel(logLevel)
	mailbox.SetLogLevel(logLevel)

	if logger != nil {
		gLogger = logger
	}
}

func Close() {
	gLogger.Close()
}

func RequestFuture(pid *actor.PID, send nrpc.IMessage, timeout time.Duration) (nrpc.IMessage, error) {
	f := RootContext.RequestFuture(pid, send, timeout)
	iRecv, err := f.Result()
	if err != nil {
		return nil, err
	}
	recv, ok := iRecv.(nrpc.IMessage)
	if !ok {
		return nil, fmt.Errorf("recv msg %#v is not a IMessage", recv)
	}
	return recv, nil
}

func ForwardToChildren(sender *actor.PID, iRecv nrpc.IMessage, iSend nrpc.IMessage, ctx actor.Context, args ...interface{}) {
	for _, pid := range ctx.Children() {
		// 转发给所有子actor
		RootContext.Send(pid, iRecv)
	}
}
